package evi.com.evi.utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import evi.com.evi.R;

/**
 * @2016年8月15日下午3:46:24
 * @author neil
 *
 * @TODO 选择样式1:时间选择（年月日模式 改为 时分模式）
 */
public class PopTime {

	private static PopupWindow popupWindow; // 必须全局：所有方法操作

	public interface DateBack { // 回调
		void sure(String date);
	}

	public void showFullScreen(Activity activity,String title,
			final DateBack callback) {
		showFullScreen(activity,title, null, callback);
	}

	/**
	 * @TODO 显示
	 */
	public void showFullScreen(Activity activity,  String title,
			String initDate, final DateBack callback) {
		if (!(popupWindow == null || !popupWindow.isShowing()))
			return;
		View view = getView(activity, title, initDate, callback);

		popupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		try {
			popupWindow.showAtLocation(activity.getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
		} catch (Exception e) {
		}
	}

	/**
	 * @TODO 核心逻辑
	 */
	private View getView(Activity activity, String title, String initDate,
			final DateBack callback) {

		View view = activity.getLayoutInflater().inflate(
				R.layout.pub_time, null);

		if (!TextUtils.isEmpty(title))
			((TextView) (view.findViewById(R.id.title))).setText(title);

		final ListView lv_year = (ListView) view.findViewById(R.id.lv_year);
		final ListView lv_month = (ListView) view.findViewById(R.id.lv_month);
		final ListView lv_day = (ListView) view.findViewById(R.id.lv_day);

		final TextView tv_year = (TextView) view.findViewById(R.id.year);
		final TextView tv_month = (TextView) view.findViewById(R.id.month);
		final TextView tv_day = (TextView) view.findViewById(R.id.day);
		final List<String> list_year = new ArrayList<String>();
		final List<String> list_month = new ArrayList<String>();
		final List<String> list_day = new ArrayList<String>();

		for (int i = 0; i <= 23; i++) {
			if(i < 10){
				list_year.add("0" + i);
			}else{
				list_year.add(i + "");
			}
		}
		for (int i = 0; i <= 59; i++) {
			if(i < 10){
				list_month.add("0" + i);
			}else{
				list_month.add(i + "");
			}
		}

//		for (int i = 1950; i <= 2050; i++) {
//			list_year.add(i + "年");
//		}
//		for (int i = 1; i <= 12; i++) {
//			list_month.add(i + "月");
//		}
//		for (int i = 1; i <= 31; i++) {
//			list_day.add(i + "日");
//		}
		list_year.add(0, "");
		list_year.add(0, "");
		list_year.add("");
		list_year.add("");
		list_month.add(0, "");
		list_month.add(0, "");
		list_month.add("");
		list_month.add("");
		list_day.add(0, "");
		list_day.add(0, "");
		list_day.add("");
		list_day.add("");

		view.findViewById(R.id.bg).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popupWindow.dismiss();
				popupWindow = null;
			}
		});
		view.findViewById(R.id.sure).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String year;
				String month;
				String day;
				year = list_year.get(lv_year.getFirstVisiblePosition() + 2);
				month = list_month.get(lv_month.getFirstVisiblePosition() + 2);
				day = list_day.get(lv_day.getFirstVisiblePosition() + 2);
//				callback.sure(year + month + day);
				callback.sure(year + ":" + month);
				popupWindow.dismiss();
				popupWindow = null;
			}
		});
		MyAdapter myAdapterYear = new MyAdapter(activity.getLayoutInflater(),
				list_year);
		MyAdapter myAdapterMonth = new MyAdapter(activity.getLayoutInflater(),
				list_month);
		final MyAdapter myAdapterDay = new MyAdapter(
				activity.getLayoutInflater(), list_day);
		lv_year.setAdapter(myAdapterYear);
		lv_month.setAdapter(myAdapterMonth);
		lv_day.setAdapter(myAdapterDay);

		lv_year.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == 0) {
					lv_year.setSelection(lv_year.getFirstVisiblePosition());
					
					String year = list_year.get(lv_year
							.getFirstVisiblePosition() + 2);
					String month = list_month.get(lv_month
							.getFirstVisiblePosition() + 2);
					int day_num = getDaysByYearMonth(year, month);
					list_day.clear();
					for (int i = 1; i <= day_num; i++) {
						list_day.add(i + "日");
					}
					list_day.add(0, "");
					list_day.add(0, "");
					list_day.add("");
					list_day.add("");
					myAdapterDay.notifyDataSetChanged();
					lv_day.setSelection(2);
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				ListView lv = (ListView) view;
				tv_year.setText(list_year.get(lv.getFirstVisiblePosition() + 2));
			}
		});
		lv_month.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == 0) {
					lv_month.setSelection(lv_month.getFirstVisiblePosition());
					
					String year = list_year.get(lv_year
							.getFirstVisiblePosition() + 2);
					String month = list_month.get(lv_month
							.getFirstVisiblePosition() + 2);
					int day_num = getDaysByYearMonth(year, month);
					list_day.clear();
					for (int i = 1; i <= day_num; i++) {
						list_day.add(i + "日");
					}
					list_day.add(0, "");
					list_day.add(0, "");
					list_day.add("");
					list_day.add("");
					myAdapterDay.notifyDataSetChanged();
					lv_day.setSelection(2);
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				ListView lv = (ListView) view;
				tv_month.setText(list_month.get(lv.getFirstVisiblePosition() + 2));
			}
		});
		lv_day.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == 0) {
					lv_day.setSelection(lv_day.getFirstVisiblePosition());
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				ListView lv = (ListView) view;
				tv_day.setText(list_day.get(lv.getFirstVisiblePosition() + 2));
			}
		});

		// 下面的代码是设置默认的时间是当前的时间，但是好像设置不成功
		if (true) {
			// 局部变量方便回收
			String year;
			String month;
			String day;
			// ^1[34578]\\d{9}$
			// ^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$
			if (initDate != null
					&& initDate
							.matches("^\\d{4}[\\-\\.]\\d{1,2}[\\-\\.]\\d{1,2}$")) {// 初始化为外部指定时间
				year = initDate.substring(0, 4);
				// 初始化数据
				if ("0123456789".contains(initDate.charAt(6) + "")) {
					month = initDate.substring(5, 7);
				} else {
					month = initDate.substring(5, 6);
				}
				if ("0123456789"
						.contains(initDate.charAt(initDate.length() - 2) + "")) {
					day = initDate.substring(initDate.length() - 2,
							initDate.length());
				} else {
					day = initDate.substring(initDate.length() - 1,
							initDate.length());
				}
			} else {
				Calendar cal = Calendar.getInstance();
				// 当前年
				year = cal.get(Calendar.YEAR) + "";
				// 当前月
				month = ((cal.get(Calendar.MONTH)) + 1) + "";
				// 当前月的第几天：即当前日
				day = cal.get(Calendar.DAY_OF_MONTH) + "";
			}
			// 根据数据设置显示位置
			for (int i = 0; i < list_year.size(); i++) {
				if (list_year.get(i).contains(year)) {
					lv_year.setSelection(i - 2);
					break;
				}
			}
			for (int i = 0; i < list_month.size(); i++) {
				if (list_month.get(i).contains(month)) {
					lv_month.setSelection(i - 2);
					break;
				}
			}
			for (int i = 0; i < list_day.size(); i++) {
				if (list_day.get(i).contains(day)) {
					lv_day.setSelection(i - 2);
					break;
				}
			}
		}
		return view;
	}

	/**
	 * 根据年 月 获取对应的月份 天数
	 * */
	public int getDaysByYearMonth(String year, String month) {
		int yy = Integer.parseInt(year.substring(0, year.length() - 1));
		int mm = Integer.parseInt(month.substring(0, month.length() - 1));
		Calendar a = Calendar.getInstance();
		a.set(Calendar.YEAR, yy);
		a.set(Calendar.MONTH, mm - 1);
		a.set(Calendar.DATE, 1);
		a.roll(Calendar.DATE, -1);
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}

	/**
	 * 
	 * @作者： neil.chen
	 * @创建时间： 2015年11月9日下午4:58:30
	 *
	 * @描述: listview适配器
	 */
	private class MyAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private List<String> list;

		public MyAdapter(LayoutInflater inflater, List<String> list) {
			this.inflater = inflater;
			this.list = list;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.pub_time_itme, null);
				holder = new ViewHolder();
				holder.tv = (TextView) convertView.findViewById(R.id.tv);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.tv.setText(list.get(position));
			return convertView;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		private class ViewHolder {
			TextView tv;
		}
	}
}
